package com.dlz.systemshop.controller;

import com.dlz.systemshop.pojo.User;
import com.dlz.systemshop.service.UserService;
import com.dlz.systemshop.utils.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 董熠涛
 * @date 2025/4/26 00:41
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public ApiResponse<String> login(@RequestBody User user){
        String token = userService.login(user);
        ApiResponse<String> stringApiResponse = new ApiResponse<>();
        if (token == null){
            stringApiResponse.error(500,"登录失败",null);
            return stringApiResponse;
        }
        stringApiResponse.oK("登录成功",token);
        return stringApiResponse;
    }

    @PostMapping("/logout")
    public ApiResponse<String> logout(HttpServletRequest request, HttpServletResponse response){
        String jwt = request.getHeader("JWT");
        if (jwt == null){
            jwt = request.getParameter("JWT");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null){
//            清空上下文
            new SecurityContextLogoutHandler().logout(request,response,authentication);
//            清除redis
            stringRedisTemplate.delete("token_"+jwt);
        }
        ApiResponse<String> stringApiResponse = new ApiResponse<>();
        stringApiResponse.oK("登出成功",null);
        return stringApiResponse;
    }
}
